package com.easy.aspect;

import com.easy.bean.Operation_log;
import com.easy.service.Operation_logService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private Operation_logService operation_logService;

    // 定义切点，拦截所有controller包下的所有类的所有方法
    @Pointcut("execution(public * com.easy.controller..*.*(..))")
    public void webLog() {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 记录请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String method = "";
        String url = "";
        String ip = "";
        String classMethod = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();
        String args = Arrays.toString(proceedingJoinPoint.getArgs());

        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            method = request.getMethod();
            url = request.getRequestURL().toString();
            ip = request.getRemoteAddr();
        }

        Object result = null;
        try {
            result = proceedingJoinPoint.proceed();
            return result;
        } finally {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            // 记录日志到文件
            logger.info("请求方法 : {}, 请求地址 : {}, IP地址 : {}, 调用方法 : {}, 请求参数 : {}, 耗时: {} ms",
                    method, url, ip, classMethod, args, duration);

            if (result != null) {
                logger.info("响应结果 : {}", result);
            }

            // 保存日志到数据库
            try {
                Operation_log operationLog = new Operation_log();
                operationLog.setMethod(method);
                operationLog.setUrl(url);
                operationLog.setIp(ip);
                operationLog.setClassMethod(classMethod);
                operationLog.setArgs(args);
                operationLog.setResponse(result != null ? result.toString() : "");
                operationLog.setDuration(duration);
                operationLog.setCreateTime(LocalDateTime.now());

                operation_logService.insert(operationLog);
            } catch (Exception e) {
                logger.error("保存操作日志到数据库失败: ", e);
            }
        }
    }
}
